<template>
  <div class="dashboard-container">
    <!-- 顶部标题 -->
    <div class="header">
      <h1>智慧洗衣平台运营大屏</h1>
      <div class="update-time">数据更新于：{{ updateTime }}</div>
    </div>

    <!-- 主要数据指标 -->
    <div class="top-stats">
      <div
          v-for="(stat, index) in statsCards"
          :key="index"
          class="stat-card"
          :style="cardStyles[index]"
      >
        <div class="card-icon">
          <i :class="stat.icon"></i>
        </div>
        <div class="card-content">
          <div class="label">{{ stat.label }}</div>
          <div class="value">{{ stat.value }}</div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="chart-row">
      <div class="chart-container">
        <div class="chart-title">订单趋势分析</div>
        <div ref="orderChart" class="chart"></div>
      </div>

      <div class="chart-container">
        <div class="chart-title">设备状态分布</div>
        <div ref="deviceChart" class="chart"></div>
      </div>
    </div>

    <!-- 底部数据 -->
    <div class="bottom-stats">
      <div class="revenue-box">
        <div class="title">总收益（元）</div>
        <div class="value">{{ formatRevenue(dashboardData.totalEarnings) }}</div>
      </div>
      <div class="service-points">
        <div class="stats-item">
          <span class="label">合作商家</span>
          <span class="value">{{ dashboardData.totalMerchants }} 家</span>
        </div>
        <div class="stats-item">
          <span class="label">自助网点</span>
          <span class="value">{{ dashboardData.totalSelfServicePoints }} 个</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'; // Added 'computed' import
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import axios from 'axios';
import _ from 'lodash';

export default {
  name: 'DashboardPage',
  setup() {
    const store = useStore();
    const router = useRouter();

    const dashboardData = ref({
      totalUsers: 0,
      totalMerchants: 0,
      totalSelfServicePoints: 0,
      totalOrders: 0,
      totalEarnings: 0,
      activeDevices: 0,
      maintenanceDevices: 0,
      lastUpdated: null,
    });

    const updateTime = ref('');
    const orderChart = ref(null);
    const deviceChart = ref(null);
    let orderChartInstance = null;
    let deviceChartInstance = null;
    let updateTimer = null;

    const cardStyles = [
      { background: 'linear-gradient(45deg, #409EFF, #79BBFF)' },
      { background: 'linear-gradient(45deg, #67C23A, #95DE64)' },
      { background: 'linear-gradient(45deg, #E6A23C, #FFD666)' },
      { background: 'linear-gradient(45deg, #F56C6C, #FF7875)' },
    ];

    const statsCards = ref([
      { label: '注册用户', value: 0, icon: 'el-icon-user' },
      { label: '总订单量', value: 0, icon: 'el-icon-s-order' },
      { label: '自助网点', value: 0, icon: 'el-icon-location' },
      { label: '活跃设备', value: 0, icon: 'el-icon-cpu' },
    ]);

    const adminInfo = computed(() => store.state.adminInfo || { username: '管理员', role: '' });

    // 初始化图表
    const initCharts = () => {
      if (orderChartInstance) orderChartInstance.dispose();
      if (deviceChartInstance) deviceChartInstance.dispose();

      orderChartInstance = echarts.init(orderChart.value);
      deviceChartInstance = echarts.init(deviceChart.value);
      updateCharts();
    };

    // 更新图表数据
    const updateCharts = () => {
      const orderOption = {
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        },
        yAxis: { type: 'value' },
        series: {
          data: [120, 200, 150, 80, 70, 110, 130], // 示例数据，可替换为真实接口数据
          type: 'line',
          smooth: true,
          areaStyle: {},
          itemStyle: { color: '#409EFF' },
        },
      };

      const deviceOption = {
        tooltip: { trigger: 'item' },
        series: {
          type: 'pie',
          radius: ['40%', '70%'],
          data: [
            { value: dashboardData.value.activeDevices, name: '正常设备', itemStyle: { color: '#67C23A' } },
            { value: dashboardData.value.maintenanceDevices, name: '维护设备', itemStyle: { color: '#F56C6C' } },
          ],
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: true,
            formatter: '{b}: {c} ({d}%)',
          },
        },
      };

      orderChartInstance.setOption(orderOption);
      deviceChartInstance.setOption(deviceOption);
    };

    // 获取数据
    const fetchData = _.debounce(async () => {
      try {
        const token = sessionStorage.getItem('token');
        if (!token) {
          ElMessage.error('未登录，请先登录');
          router.push('/login');
          return;
        }

        const response = await axios.get('/api/dashboard/stats', {
          headers: {
            Authorization: `Bearer ${token}`,
            Role: adminInfo.value.role || '',
            Username: encodeURIComponent(adminInfo.value.username || ''),
          },
        });

        dashboardData.value = response.data;
        updateTime.value = new Date(dashboardData.value.lastUpdated).toLocaleString('zh-CN');

        // 更新卡片数据
        statsCards.value[0].value = dashboardData.value.totalUsers;
        statsCards.value[1].value = dashboardData.value.totalOrders;
        statsCards.value[2].value = dashboardData.value.totalSelfServicePoints;
        statsCards.value[3].value = dashboardData.value.activeDevices;

        updateCharts();
      } catch (error) {
        const errorMsg = error.response?.data?.message || '获取仪表盘数据失败';
        ElMessage.error(errorMsg);
        console.error(
            `Failed to fetch dashboard stats for role: ${adminInfo.value.role}, username: ${adminInfo.value.username}`,
            error
        );
        if (error.response?.status === 401) {
          router.push('/login');
        }
      }
    }, 300);

    // 格式化金额
    const formatRevenue = (value) => {
      if (!value) return '0.00';
      return Number(value).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      });
    };

    // 初始化
    onMounted(() => {
      initCharts();
      fetchData();
      updateTimer = setInterval(fetchData, 30000); // 30秒刷新
    });

    // 清理
    onBeforeUnmount(() => {
      if (orderChartInstance) orderChartInstance.dispose();
      if (deviceChartInstance) deviceChartInstance.dispose();
      if (updateTimer) clearInterval(updateTimer);
    });

    return {
      dashboardData,
      updateTime,
      statsCards,
      cardStyles,
      orderChart,
      deviceChart,
      formatRevenue,
    };
  },
};
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.header h1 {
  font-size: 28px;
  color: #333;
  margin: 0;
}

.update-time {
  color: #666;
  font-size: 14px;
}

.top-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  padding: 20px;
  border-radius: 8px;
  color: #fff;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-icon {
  font-size: 40px;
  margin-right: 20px;
}

.card-content .label {
  font-size: 16px;
  margin-bottom: 8px;
}

.card-content .value {
  font-size: 24px;
  font-weight: bold;
}

.chart-row {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 15px;
}

.chart {
  height: 400px;
}

.bottom-stats {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 20px;
}

.revenue-box {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.revenue-box .title {
  font-size: 16px;
  color: #666;
  margin-bottom: 10px;
}

.revenue-box .value {
  font-size: 32px;
  color: #67c23a;
  font-weight: bold;
}

.service-points {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  justify-content: space-around;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stats-item {
  text-align: center;
}

.stats-item .label {
  display: block;
  color: #666;
  margin-bottom: 8px;
}

.stats-item .value {
  font-size: 20px;
  color: #409eff;
  font-weight: bold;
}
</style>